package com.cskaoyan.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cskaoyan.bean.model.MarketCategory;
import com.cskaoyan.bean.model.MarketCategoryExample;
import com.cskaoyan.bean.resp.CatalogIndexVo;
import com.cskaoyan.bean.resp.CurrentCatalogVo;
import com.cskaoyan.mapper.MarketCategoryMapper;

/**
 * @author Joe
 * @since 2024/04/27 18:24
 */
@Service
public class CatalogServiceImpl implements CatalogService {
    @Autowired
    MarketCategoryMapper marketCategoryMapper;
    @Autowired
    CategoryService categoryService;

    @Override
    public CurrentCatalogVo current(Integer id) {
        // 通过id查询当前一级分类
        MarketCategory currentCategoryL1 = marketCategoryMapper.selectByPrimaryKey(id);
        if (currentCategoryL1 == null || currentCategoryL1.getDeleted().equals(true)) {
            return null;
        }

        // 查询当前一级分类下的所有二级分类
        MarketCategory currentCategoryL2 = new MarketCategory();
        List<MarketCategory> currentCategoryL2List = categoryService.queryByPid(currentCategoryL1.getId());

        CurrentCatalogVo currentCatalogVo = new CurrentCatalogVo();

        currentCatalogVo.setCurrentCategory(currentCategoryL1);
        currentCatalogVo.setCurrentSubCategory(currentCategoryL2List);

        return currentCatalogVo;
    }

    @Override
    public CatalogIndexVo index() {
        CatalogIndexVo catalogIndexVo = new CatalogIndexVo();

        // 查询所有的一级分类
        MarketCategoryExample example = new MarketCategoryExample();
        example.createCriteria().andDeletedEqualTo(false).andLevelEqualTo("L1");
        List<MarketCategory> categoryList = marketCategoryMapper.selectByExample(example);

        // 检查是否获取到一级分类列表
        if (categoryList == null || categoryList.isEmpty()) {
            // 处理未找到一级分类的情况，抛出异常
             throw new RuntimeException("未找到一级分类");
        }

        // 选择第一个一级分类作为默认分类
        MarketCategory defaultCategory = categoryList.get(0);

        try {
            // 获取当前分类及其子分类
            CurrentCatalogVo current = current(defaultCategory.getId());

            // 设置当前分类和子分类到Vo对象
            catalogIndexVo.setCurrentCategory(current.getCurrentCategory());
            catalogIndexVo.setCurrentSubCategory(current.getCurrentSubCategory());
        } catch (Exception e) {
            // 处理获取当前分类时发生的异常
            throw new RuntimeException("获取当前分类失败: " + e.getMessage());
        }

        // 设置一级分类列表到Vo对象
        catalogIndexVo.setCategoryList(categoryList);

        return catalogIndexVo;
    }
}